//
//  MeditationViewController.m
//  AndCampus
//
//  Created by 史宵宵 on 2018/1/3.
//  Copyright © 2018年 史宵宵. All rights reserved.
//

#import "MeditationViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "XXAVPlayer.h"

@interface MeditationViewController ()<XXAVPlayerDelegate,AVAudioPlayerDelegate>
//@property (nonatomic,strong) AVPlayer *player;
//@property (nonatomic,strong) AVPlayerItem * songItem;
@property (nonatomic,weak) XXAVPlayer *player;
@property (nonatomic,strong) id timeObserve;
//@property (nonatomic,weak) UISlider *meditionSlider;
@end

@implementation MeditationViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    UIImage *image = [UIImage imageNamed:@"meditation_bg"];
    self.view.layer.contents = (id) image.CGImage;
    self.title = @"冥想屋";
    self.meditionSlider.continuous = NO;//当放开手., 值才确定下来
    [self.meditionSlider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    [self creatPlayer];
//    [self initSlider];
//    [self player];
}
- (void)creatPlayer{
//    MyLog(@"%@",self.megaphoneInfo.audio);
//    NSURL * url  = [NSURL URLWithString:@"http://mtest.51ts.cn/media/BeatIt.mp3"];
//    AVPlayerItem * songItem = [[AVPlayerItem alloc]initWithURL:url];
//    [songItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];// 监听status属性
//    [songItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];// 监听loadedTimeRanges属性
//    self.songItem = songItem;
//    AVPlayer * player = [[AVPlayer alloc]initWithPlayerItem:songItem];
//    self.player = [AVPlayer playerWithPlayerItem:songItem];
    NSString *path = self.megaphoneInfo.audio;
    XXAVPlayer *playView = [[XXAVPlayer alloc] initWithFrame:CGRectZero];
//    playView.userInteractionEnabled = YES;
//    [playView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(isHiddenSlider)]];
    playView.delegate = self;
    [playView pause];
    [self.view addSubview:playView];
    
    
    NSString *videoPath = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:videoPath];
    [playView setupPlayerWith:url];
    
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:songItem];
    
    self.player = playView;
    
}
- (void)initSlider{
    
    UISlider *mySlider = [[UISlider alloc] initWithFrame:CGRectMake(50, kScreenH - 50,kScreenW - 150 ,30) ];//高度设为40就好,高度代表手指触摸的高度.这个一定要注意
    mySlider.minimumValue = 0.0;//下限
    mySlider.maximumValue = 50.0;//上限
    mySlider.value = 0;//开始默认值
    mySlider.backgroundColor =[UIColor clearColor];//测试用,
    [mySlider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    mySlider.continuous = NO;//当放开手., 值才确定下来
    [self.view addSubview:mySlider ];
    self.meditionSlider = mySlider;
    
//    UILabel *timeLabel = [[UILabel alloc]init];
//    timeLabel.frame = CGRectMake(CGRectGetMaxX(mySlider.frame) + 5, 15, 120, 20);
//    timeLabel.font = [UIFont systemFontOfSize:12];
//    timeLabel.textColor = [UIColor whiteColor];
//    [ bgView addSubview:timeLabel];
//    self.timeLabel = timeLabel;
}
- (NSString *)convertTime:(CGFloat)second{
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if (second/3600 >= 1) {
        [formatter setDateFormat:@"HH:mm:ss"];
    } else {
        [formatter setDateFormat:@"mm:ss"];
    }
    NSString *showtimeNew = [formatter stringFromDate:d];
    return showtimeNew;
}
- (IBAction)meditationStart:(id)sender {
    UIButton *button = sender;
    button.selected = !button.selected;
    
    if (button.selected) {
        MyLog(@"播放");
        [self.player play];
     }else{
        MyLog(@"暂停");
        [self.player pause];
    }
}
//- (void)sliderValueChanged:(UISlider *)slider{
//    MyLog(@"%f",slider.value);
//    [self.player seekToTime:CMTimeMake(slider.value, 100)];
//
//}
// LPAVPlayer delegate  ----- 刷新数据
- (void)refreshDataWith:(NSTimeInterval)totalTime Progress:(NSTimeInterval)currentTime LoadRange:(NSTimeInterval)loadTime
{
    
    //    [self.loadProgress setProgress:(loadTime/totalTime) animated:YES];
    //
    [self.meditionSlider setValue:currentTime animated:YES];
    //
//    self.timeLabel.text = [NSString stringWithFormat:@"%@/%@",[self otherConvertTimeFormat:currentTime],[self otherConvertTimeFormat:totalTime]];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"]) {
        if ([playerItem status] == AVPlayerStatusReadyToPlay) {
            NSLog(@"AVPlayerStatusReadyToPlay");
//            self.stateButton.enabled = YES;
//            CMTime duration = self.songItem.duration;// 获取视频总长度
//            CGFloat totalSecond = playerItem.duration.value / playerItem.duration.timescale;// 转换成秒
//            [self.player convertTime:totalSecond];// 转换成播放时间
//            [self.xxPlayer seekToTime:CMTimeMake(totalSecond, 100)];
            
//            NSLog(@"movie total duration:%f",CMTimeGetSeconds(duration));
//            [self monitoringPlayback:self.songItem];// 监听播放状态
        }else if ([playerItem status] == AVPlayerStatusReadyToPlay){
            self.meditionSlider.maximumValue = self.player.totalTime;
            self.meditionSlider.value = 0;
            NSLog(@"KVO：未知状态，此时不能播放");
        }else if ([playerItem status] == AVPlayerStatusUnknown){
            NSLog(@"KVO：准备完毕，可以播放");
        }else if ([playerItem status] == AVPlayerStatusFailed) {
            NSLog(@"AVPlayerStatusFailed");
        }
    }
}
- (void)sliderValueChanged:(UISlider *)slider{
    MyLog(@"%f",slider.value);
    [self.player seekPlayerTimeTo:slider.value];
}
- (void)monitoringPlayback:(AVPlayerItem *)playerItem {
//    __weak typeof(self) unself = self;
//    id timeObserve = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time) {
//        CGFloat currentSecond = playerItem.currentTime.value/playerItem.currentTime.timescale;// 计算当前在第几秒
//        [unself.meditionSlider setValue:currentSecond animated:YES];
//        NSString *timeString = [unself convertTime:currentSecond];
//        MyLog(@"----------%@",timeString);
//    }];
//    MyLog(@"----------%@",timeObserve);
}
- (void)dealloc{
//    if (self.timeObserve) {
//        [self.player removeTimeObserver:self.timeObserve];
//        self.timeObserve = nil;
//    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
